import { tableKey } from '@/utils/utils';
import { Table } from 'antd';
import React, { useEffect, useImperativeHandle, useState, forwardRef } from 'react';
import useData from './data';

export interface columnsItem {
  title: any;
  dataIndex?: string;
  render: React.ReactNode;
  width?: number;
  key?: string | number;
  align?: string;
}

interface TablesProps {
  url: string;
  columns: columnsItem[];
  childRef: any;
  option?: any;
  footer?: any;
  getValue?: any;
}

const Tables: React.FC<TablesProps> = props => {
  const [data, setQuery, isLoading, isError, defaultList] = useData(props?.url, props?.option);
  const [columns, setColumns] = useState<any>([]);
  const [options, setOption] = useState<any>({});
  useEffect(() => {
    setColumns(() => {
      return props?.columns.map(el => ({
        ellipsis: true,
        align: 'center',
        width: el.key == 'key' ? 80 : false,
        className: el.key == 'key' ? 'col_dataIndex_1' : false,
        ...el,
      }));
    });
    let { getValue } = props;

    // 把当前数据传给父组件
    getValue &&
      getValue({
        ...data,
        defalut: defaultList,
      });
  }, [data]);
  /**
   * 分页
   * @param current
   * @param pageSize
   */
  const onChange = (current: number | undefined, pageSize: number | undefined): void => {
    setQuery({
      ...options,
      pageIndex: current ? current : 1,
      pageSize,
    });
  };

  useImperativeHandle(
    props.childRef,
    () => ({
      setQuery: (parmas: any) => {
        setOption(parmas);
        setQuery({ pageIndex: data?.current || 1, ...parmas, defalut: 2 });
      },
    }),
    [data, isLoading],
  );

  if (!isError) {
    tableKey(data?.pagedItems ?? [], data?.current, data?.pageSize);
  }

  const { footer } = props;

  return (
    <div>
      <Table
        loading={isLoading}
        dataSource={data?.pagedItems ?? []}
        columns={columns}
        footer={footer ? footer : false}
        pagination={{
          current: data?.current,
          hideOnSinglePage: true,
          onChange,
          total: data?.totalCount,
        }}
      />
    </div>
  );
};

export default Tables;
